package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constrant.MessageConstant;
import com.itheima.entity.Result;

import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;


/**
 * @author FCJ
 * @date 2020-01-11 9:44
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Reference
    private UserService userService;

    @RequestMapping("/getUsername")
    public Result getUsername() {
        //spring security 完成认证后，会将当前用户信息保存到框架提供的上下文对象
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (user != null) {
            String username = user.getUsername();
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS, username);
        }
        return new Result(false, MessageConstant.GET_USERNAME_FAIL);
    }

    @RequestMapping("/editPassword")
    public Result editPassword(@RequestBody Map map) {

        try {
            if (userService.updatePassword(map)) {
                return new Result(true, "密码修改成功，请重新登入");
            } else {
                return new Result(false, "用户名或者密码错误");

            }
        } catch (Exception e) {
            return new Result(false, "用户名或者密码错误");
        }

    }
}
